var module = angular.module("manga", []);
module.factory('mangaStore', function($http, $waitDialog) {
    var readUrl = 'https://secure.openkeyval.org/';
    var writeUrl = 'https://secure.openkeyval.org/store/?';
    var mangaDetailUrl = 'http://manga.zoha.com.au/MangaService.svc/jsonp/GetMangaStoryDetail?key=kissmanga&url=http://kissmanga.com/Manga/Bucchigiri-CA&callback=JSON_CALLBACK';
    var popularMangaUrl = 'http://manga.zoha.com.au/MangaService.svc/jsonp/GetPopularManga?key=kissmanga&number=20&callback=JSON_CALLBACK';
    function readMangaDetail() {
        $waitDialog.show();
        $http({method: "JSONP", url:mangaDetailUrl}).then(function(response){
            $waitDialog.hide();
            return response.data;
        });
    }
    function readPopularManga(numberToFetch, callback){
        $waitDialog.show();
        var tempPopularMangaUrl = popularMangaUrl.replace(":number", numberToFetch);
        $http({method: "JSONP", url:popularMangaUrl}).then(function(response){
            $waitDialog.hide();
            callback(response.data);
        });
    }

    return {
        readMangaDetail: readMangaDetail,
        readPopularManga: readPopularManga
    }

});

module.controller('MangaController', function($scope, $navigate, mangaStore) {
    $scope.data = {
        mangaList:[]
    };
    $scope.currentNumberFetch = '20';
    $scope.back = function() {
        $navigate('back');
    };
    $scope.refreshMangaList = function() {
        mangaStore.readPopularManga($scope.currentNumberFetch, function(data){
            $scope.mangaList = data;
        });
    };
});